package uutalk.netcloud.talk.app.ui.Activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.app.BootstrapApp;

import uutalk.netcloud.talk.app.ui.adapter.JoinedGroupsAdapter;
import uutalk.netcloud.talk.base.android.BaseActivity;
import uutalk.netcloud.talk.base.mqtt.MQTTManager;
import uutalk.netcloud.talk.base.mqtt.PublishFactory;
import uutalk.netcloud.talk.base.mqtt.event.MqttMessageEvent;
import uutalk.netcloud.talk.base.mqtt.model.Publication;
import uutalk.netcloud.talk.base.util.ImageUtil;
import uutalk.netcloud.talk.base.util.thirdpart.EventMamager;
import uutalk.netcloud.talk.base.util.thirdpart.UserManager;
import uutalk.netcloud.talk.base.util.view.ToastUtil;
import uutalk.netcloud.talk.model.BussinessBeanFactory;
import uutalk.netcloud.talk.model.bean.CMDConstant;
import uutalk.netcloud.talk.model.bean.GroupInfoBean;
import uutalk.netcloud.talk.model.bean.GroupListWrap;
import uutalk.netcloud.talk.model.bean.QuitGroupRsp;
import uutalk.netcloud.talk.model.bean.SimpleEvent;
import uutalk.netcloud.talk.model.bean.SimpleEventType;

import static uutalk.netcloud.talk.model.bean.ScanResult.groupId;

/**
 * Created by hujie on 17/3/29.
 */

public class ScanJoinActivity extends BaseActivity {


    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    JoinedGroupsAdapter adapter;
    int deletePosition = -1;

    @Override
    public void init() {
        CaptureFragment captureFragment = new CaptureFragment();

        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.scan_join_camera);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        /**
         * 替换我们的扫描控件
         */
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
        initRecycleView();

        requestHasJoinedGroups();
    }

    @Override
    public boolean autoBindEvent() {
        return true;
    }


    private void initRecycleView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMqttMessageEvent(MqttMessageEvent event) {
        if (CMDConstant.GET_USER_JOINED_GROUPS_RESP.equals(event.getMessage().getCmd())) {
            progressHudUtil.dismissProgressHud();
            //获取加入过的群组

            GroupListWrap listWrap = JSON.parseObject(event.getMessage().toString(), GroupListWrap.class);
            if (listWrap.isOk()) {


                setAdapter(listWrap.getGroup_list());


            } else {
                ToastUtil.makeToast(listWrap.error_msg);
            }
        }
        //退出群
        if (CMDConstant.QUIT_GROUP_RESP_CMD.equals(event.getMessage().getCmd()) || CMDConstant.DISMISS_GROUP_RESP_CMD.equals(event.getMessage().getCmd())) {
            if (deletePosition < 0) {
                return;
            }
            progressHudUtil.dismissProgressHud();
            QuitGroupRsp group = JSON.parseObject(event.getMessage().toString(), QuitGroupRsp.class);
            if (group.isOk()) {
                EventMamager.getInstance().postEvent(SimpleEventType.JOIN_ACTIVE_GROUP_RESP);
                if (deletePosition >= 0) {
                    adapter.notifyItemRemoved(deletePosition);
                }
                ToastUtil.makeToast("删除成功");
                finish();
            } else {
                ToastUtil.makeToast(group.getError_msg());
            }

        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SimpleEvent event) {

        if (event.type == SimpleEventType.ON_JOINED_GROUP_CLICK) {
            deletePosition = -1;
            groupId = adapter.getItem(event.intEvent).getGroup_id();
            EventMamager.getInstance().postEvent(SimpleEventType.SCAN_GROUP_SUCCESS);
            finish();
        }

        if (event.type == SimpleEventType.ON_JOINED_GROUP_DELETE_CLICK) {
            deletePosition = event.intEvent;
            GroupInfoBean groupInfoBean = adapter.getItem(event.intEvent);
            requestDeleteGroup(groupInfoBean.getOwner_id(), groupInfoBean.getGroup_id());
        }


    }

    private void requestDeleteGroup(String groupOwen, String groupId) {
        boolean isOwen = false;
        if (groupOwen.equals(UserManager.getInstance().getUserInfo().getUser_id())) {
            isOwen = true;
        }
        if (MQTTManager.getInstance().isConnected()) {
            progressHudUtil.showProgressHud();
            Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createQuitActivityBean(isOwen ?
                    CMDConstant.DISMISS_GROUP_CMD : CMDConstant.QUIT_GROUP_CMD, groupId));
            MQTTManager.getInstance().publish(publication);
        } else {
            ToastUtil.makeToast("请求失败,请重试");

        }

    }

    private void setAdapter(List<GroupInfoBean> groups) {
        adapter = new JoinedGroupsAdapter(groups);
        adapter.bindToRecyclerView(recyclerView);
        adapter.notifyDataSetChanged();

    }


    /**
     * 获取加入过的群组
     */
    private void requestHasJoinedGroups() {
        if (MQTTManager.getInstance().isConnected()) {
            progressHudUtil.showProgressHud();
            Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createJoinedGroups());
            MQTTManager.getInstance().publish(publication);
        } else {
            ToastUtil.makeToast("获取加入过的群组失败");
        }
    }


    @Override
    public boolean supportActionbar() {
        return false;
    }

    @Override
    public int layoutId() {
        return R.layout.scan_join_group;
    }


    @Override
    public void setStatusColor() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1000) {
            if (data != null) {
                Uri uri = data.getData();
                try {
                    CodeUtils.analyzeBitmap(ImageUtil.getImageAbsolutePath(mActivity, uri), new CodeUtils.AnalyzeCallback() {
                        @Override
                        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
                            parseScanString(result);
                        }

                        @Override
                        public void onAnalyzeFailed() {
                            ToastUtil.makeToast("解析失败");
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            parseScanString(result);
        }

        @Override
        public void onAnalyzeFailed() {
            ToastUtil.makeToast("扫描失败");
        }
    };


    private void parseScanString(String result) {

        if (!TextUtils.isEmpty(result)) {
            //活动二维码
            if (result.startsWith("HD")) {
                result = result.substring(2);
                groupId = result;
                if (UserManager.getInstance().getLoginInfo() == null) {
                    //未登录 先以游客身份登录
                    String deviceId = BootstrapApp.get().uuid();
                    String password = deviceId;
                    //startActivity(LoginActivityAutoBundle.builder().isFromScan(true).deviceId(deviceId).password(password).userType("2").build(mActivity));
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    EventMamager.getInstance().postEvent(SimpleEventType.SCAN_GROUP_SUCCESS);
                    finish();
                }
            }
        }

    }


    @Override
    public int getThemeId() {
        return R.style.TranlucentStatusTheme;
    }
}
